package com.diyphonegadgets.robot.wifi;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import com.diyphonegadgets.robot.MainActivity;
import com.diyphonegadgets.robot.Properties;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

/**
 * Android Accelerometer Sensor Manager Archetype
 * 
 * @author antoine vianey under GPL v3 :
 *         http://www.gnu.org/licenses/gpl-3.0.html
 */
public class CommandManager {

	// you could use an OrientationListener array instead
	// if you plans to use more than one listener
	
	SharedPreferences sp;

	public static CommandListener listener;
	public static int updateInterval = 80;

	public static String destinationIP ;
	public static String localIP = "10.0.2.2";
	public static int sendPort ;
	public static int receivePort;
	


	public static void init() {
		
	  
		sendPort = Integer.parseInt(MainActivity.getSharedPreferences().getString("send ip", "5550"));
		receivePort = Integer.parseInt(MainActivity.getSharedPreferences().getString("receive ip", "5551"));
		destinationIP = MainActivity.getSharedPreferences().getString("destination ip", "192.168.43.209");
		
		
		Log.d("TCPCameraStreamingServer", "starts");

		
		
		

		Log.d("Server", "starts");

		receiveRealTimeData();

		Log.d("Client", "starts");

		sendRealTimeData();

	}

	public static String getMyIPAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress())
						return inetAddress.getHostAddress();
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static synchronized void startListening(
			CommandListener commandListener) {

		listener = commandListener;

	}

	private static void sendRealTimeData() {

		Thread cThread = new Thread(new TCPClient());
		cThread.start();
	}

	private static void receiveRealTimeData() {

		Thread sThread = new Thread(new TCPServer());
		sThread.start();
	}
	



}
